import React from 'react'
import { useSelector } from 'react-redux'
import type { RootState } from '../store'
import { useLocation, Navigate } from'react-router-dom'


const Permission: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const location = useLocation()
  const userInfo = useSelector((state: RootState) => state.user.userInfo)
  // 获取当前用户的所有权限
  const permission = useSelector((state: RootState) => state.user.userInfo?.permission ?? [])
  // 根据当前访问的地址去权限中查找是否有此权限
  const isPermission = permission.find((item) => item.path === location.pathname)

  if (userInfo === null) return null
  if (isPermission) return children
  return <Navigate to="/403" />
}

export default Permission